import time

import requests
from cv2 import cv2
from selenium import webdriver
from selenium.webdriver import ActionChains


def img():
    # 读取大图
    big_rgb = cv2.imread('./register_img/big.png')

    # 进行灰度处理
    gig_gray = cv2.cvtColor(big_rgb, cv2.COLOR_BGR2GRAY)

    # 读取小图
    small_rgb = cv2.imread('./register_img/small.png', 0)

    # 匹配小图在大图中的位置
    res = cv2.matchTemplate(gig_gray, small_rgb, cv2.TM_CCOEFF_NORMED)

    # 匹配最左边的结果和最右边的结果
    value = cv2.minMaxLoc(res)
    # 需要滑动的距离
    x = value[2][0]
    # 缩放比例
    x = int(x * 280 / 680)

    # 在减去滑块距离左边的位置
    x = x - 22
    return x


# 创建浏览器对象
driver = webdriver.Chrome()

# 打开网站
driver.get('https://my.pclady.com.cn/users/mobileRegister.jsp')
# 添加隐式等待1秒钟
driver.implicitly_wait(1)
# 点击QQ登录
driver.find_element_by_xpath('//div[@class="card-chw card-a-chw clearfix"]//a[2]/span').click()

# 进入到iframe中
driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="ptlogin_iframe"]'))
# 点击账号密码登录
driver.find_element_by_xpath('//*[@id="switcher_plogin"]').click()

# 填写登录信息
driver.find_element_by_xpath('//*[@id="u"]').send_keys('2391852095')
time.sleep(0.5)
driver.find_element_by_xpath('//*[@id="p"]').send_keys('kjpk6646')
time.sleep(0.5)

driver.find_element_by_xpath('//*[@id="login_button"]').click()

time.sleep(0.5)

# 进入到iframe中
driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="tcaptcha_iframe"]'))

while True:
    # 获取验证码图片
    big_ele = driver.find_element_by_xpath('//*[@id="slideBg"]')
    small_ele = driver.find_element_by_xpath('//*[@id="slideBlock"]')

    # 获取图片下载地址
    big_src = big_ele.get_attribute('src')
    small_src = small_ele.get_attribute('src')

    # 下载图片保存到本地
    big_con = requests.get(big_src).content
    small_con = requests.get(small_src).content

    # 将图片保存到本地
    with open('./register_img/big.png', 'wb') as f:
        f.write(big_con)

    with open('./register_img/small.png', 'wb') as f:
        f.write(small_con)

    # 将浏览器设置为全屏状态
    driver.maximize_window()

    # 获取滑块移动的位置
    x = img()

    # 创建滑动对象
    action = ActionChains(driver)

    # 按住小图 perfrom使操作生效
    action.click_and_hold(small_ele).perform()

    # 拖动到指定位置
    action.move_by_offset(x, 0).perform()

    # 放开鼠标
    action.release().perform()

    # 添加重试
    time.sleep(2)
    try:
        driver.find_element_by_xpath('//*[@id="e_reload"]').click()
        time.sleep(1)
    except Exception as f:
        break

# 关闭浏览器
driver.quit()